extern alias JB;

namespace StyleCop.For.ReSharper.Extensions
{
    #region Using Directives

    using System;

    using JetBrains.Application;
    using JetBrains.ReSharper.Psi.CSharp.Parsing;
    using JetBrains.ReSharper.Psi.ExtensionsAPI;
    using JetBrains.ReSharper.Psi.ExtensionsAPI.Tree;
    using JetBrains.ReSharper.Psi.Tree;

    #endregion

    ///<summary>
    /// Extension Methods for ITreeNode types
    ///</summary>
    public static class ITreeNodeExtensions
    {
        /// <summary>
        /// Inserts a newline after the Node provided.
        /// </summary>
        /// <param name="currentNode">
        /// The node to insert after.
        /// </param>
        /// <returns>
        /// An ITreeNode that has been inserted.
        /// </returns>
        public static ITreeNode InsertNewLineAfter(this ITreeNode currentNode)
        {
            LeafElementBase leafElement = GetLeafElement();
            using (WriteLockCookie.Create(true))
            {
                LowLevelModificationUtil.AddChildAfter(currentNode, new[] { leafElement });
            }
            return leafElement;
        }

        /// <summary>
        /// Inserts a newline in front of the Node provided.
        /// </summary>
        /// <param name="currentNode">
        /// The node to insert in front of.
        /// </param>
        /// <returns>
        /// The inserted ITreeNode.
        /// </returns>
        public static ITreeNode InsertNewLineBefore(this ITreeNode currentNode)
        {
            LeafElementBase leafElement = GetLeafElement();

            using (WriteLockCookie.Create(true))
            {
                LowLevelModificationUtil.AddChildBefore(currentNode, new[] { leafElement });
            }
            return leafElement;
        }

        /// <summary>
        /// Returns a LeafElementBase which contains a NewLine character.
        /// </summary>
        /// <returns>LeafElementBase containing a NewLine character.</returns>
        private static LeafElementBase GetLeafElement()
        {
            var newText = Environment.NewLine;
            return TreeElementFactory.CreateLeafElement(CSharpTokenType.NEW_LINE, new JB::JetBrains.Text.StringBuffer(newText), 0, newText.Length);
        }
    }
}